package com.example.mobile2021606163crw0519;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private TextView tvMainContent;
    private String urlString  = "http://10.110.147.117:3000/news";
    //2.定义OkhttpClient网络访问对象
    private OkHttpClient okHttpClient = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        TextView textView=(TextView)findViewById(R.id.tvMainContent);
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());
        //1.创建子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //3.根据链接地址创建访问请求对象
                Request request = new Request.Builder()
                        .url(urlString)
                        .build();
                //4.将网络请求对象添加到okhttpClient对象的call中
                Call call = okHttpClient.newCall(request);
                //5.同步方式访问网络，直接执行，从反馈对象response中获取结果（同步网络访问）
//                try {
//                    Response response = call.execute();
//                    String result = response.body().string();
//                    Log.i("TAG", result);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
                //5.异步网络访问，在call执行队列中定义回调方法，用于处理访问反馈结果，待队列闲时执行
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        //6.从反馈对象response中获取结果，然后调用UI主线程方法，将结果赋值给界面控件
                        String result = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvMainContent.setText(result);
                            }
                        });
                    }
                });
            }
        }).start();
    }

    private void initView() {
        tvMainContent = (TextView) findViewById(R.id.tvMainContent);
    }
}